<?php

/**
 * @Author: king
 * @Date:   2019-05-01 21:35:42
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-07 15:44:38
 */

namespace App\Http\Controllers\Api\v3;

use App\Http\Controllers\Api\BaseController;
use AstroTool\Cache\ProblemAndAnswer;
use App\Models\Api\Recode;
use App\Models\Api\LanmeiCommentTag;
use App\Models\Api\LanmeiCounselor;
use App\Models\Api\LanmeiCounselorAnswer;
use App\Models\Api\LanmeiCounselorCheck;
use App\Models\Api\LanmeiCounselorExercise;
use App\Models\Api\LanmeiCounselorExerciseRecord;
use App\Models\Api\LanmeiCounselorExerciseType;
use App\Models\Api\LanmeiCounselorGrabRecord;
use App\Models\Api\LanmeiCounselorProblem;
use App\Models\Api\LanmeiCounselorInfo;
use App\Models\Api\LanmeiTag;
use App\Models\Api\LanmeiUserBindAlipay;
use App\Models\Api\LanmeiUserCounselorStatus;
use App\Tools\Validates\Counselor;
use Illuminate\Http\Request;
use Cache;

/**
 * 咨询师相关接口
 * Class Counselor
 * @package App\Http\Controllers\Api\v3
 */
class CounselorController extends BaseController
{
    // TODO 认证信息加入队列

    /**
     * 咨询师筛选条件接口
     * @return response\Json
     */
    public function CounselorOption()
    {
        $option_info = config('counselor.option_type');

        return show(config('code.success'), '获取成功', $option_info);
    }

    /**
     * 咨询师列表接口.可筛选
     * @return response\Json
     * @throws \Exception
     */
    public function index(Request $request)
    {
        $param = [
            'type' => $request->input('type', 0), //类型【0=>全部,1=>占星师,2=>占卜师】
            'price' => $request->input('price', 0), //价格
            'level' => $request->input('level', 0), //等级
            'grade' => $request->input('grade', 0), //评分
            'search' => $request->input('search', ''), //搜索
            'filter_self' => $request->input('filter_self', 0),
            'page' => $request->input('page', 1),
        ];

        $validate = new Counselor();
        if ($validate->scene('index')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $param['uid'] = (int)$request->uid;
        $LanmeiCounselor = new LanmeiCounselor();
        $data = $LanmeiCounselor->getCounselorLists($param);

        $array = [
            'total' => $data['total'],
            'per_page' => $data['per_page'],
            'current_page' => $data['current_page'],
            'last_page' => $data['last_page'],
            'data' => []
        ];

        if ($data['data']) {
            foreach ($data['data'] as $datum) {
                //若没有进行类型筛选,就显示符合筛选的价格
                if ($param['type'] == 0) {
                    switch (true) {
                        case $param['price'] == 1:
                            if (0 < $datum['divination_price'] && $datum['divination_price'] <= 100) {
                                $price = $datum['divination_price'];
                            } else {
                                $price = $datum['stargazer_price'];
                            }
                            break;
                        case $param['price'] == 2:
                            if (100 < $datum['divination_price'] && $datum['divination_price'] <= 300) {
                                $price = $datum['divination_price'];
                            } else {
                                $price = $datum['stargazer_price'];
                            }
                            break;
                        case $param['price'] == 3:
                            if (300 < $datum['divination_price'] && $datum['divination_price'] <= 500) {
                                $price = $datum['divination_price'];
                            } else {
                                $price = $datum['stargazer_price'];
                            }
                            break;
                        case $param['price'] == 4:
                            if (500 < $datum['divination_price']) {
                                $price = $datum['divination_price'];
                            } else {
                                $price = $datum['stargazer_price'];
                            }
                            break;
                        default:
                            //若用户既是占星师又是占卜师则显示最低价格
                            if ($datum['divination_level'] > 0 && $datum['stargazer_level'] > 0) {
                                if ($datum['divination_level'] < $datum['stargazer_level']) {
                                    $price = $datum['divination_price'];
                                } else {
                                    $price = $datum['stargazer_price'];
                                }
                            } //否则哪个有等级就显示哪个
                            else {
                                if ($datum['divination_level'] > 0) {
                                    $price = $datum['divination_price'];
                                } else {
                                    $price = $datum['stargazer_price'];
                                }
                            }
                            break;
                    }
                } //有类型筛选就显示最低价
                else {
                    //若用户既是占星师又是占卜师则显示最低价格
                    if ($datum['divination_level'] > 0 && $datum['stargazer_level'] > 0) {
                        if ($datum['divination_level'] < $datum['stargazer_level']) {
                            $price = $datum['divination_price'];
                        } else {
                            $price = $datum['stargazer_price'];
                        }
                    } //否则哪个有等级就显示哪个
                    else {
                        if ($datum['divination_level'] > 0) {
                            $price = $datum['divination_price'];
                        } else {
                            $price = $datum['stargazer_price'];
                        }
                    }
                }

                $array['data'][] = [
                    'avatar' => $datum['avatar'],
                    'nickname' => $datum['nickname'],
                    'is_hot' => $datum['is_hot'],
                    'divination_level' => $datum['divination_level'],
                    'stargazer_level' => $datum['stargazer_level'],
                    'grade' => $datum['star_level'],
                    'intro' => $datum['intro'],
                    'counselor_num' => $datum['counselor_num'],
                    'price' => $price,
                    'cid' => $datum['id']
                ];
            }
        }

        return show(config('code.success'), '获取成功', $array);
    }


    /**
     * 热门咨询师接口
     * @return response\Json
     * @throws \Exception
     */
    public function HotCounselor()
    {
        $LanmeiCounselor = new LanmeiCounselor();
        $LanmeiCounselorAnswer = new LanmeiCounselorAnswer();
        //获取后台推荐热门咨询师
        $HotCounselor = $LanmeiCounselor->getHotCounselor();
        if ($HotCounselor === false) {
            return show(config('code.error'), $LanmeiCounselor->getError());
        }

        $data['hot'] = [];

        //若后台设置的热门咨询师不足10个,获取回答次数较多的进行追加显示
        if (count($HotCounselor) < 10) {
            //获取回答次数多的咨询师
            $AnswerNum = $LanmeiCounselorAnswer->getWeekBestCounselor();
            if ($AnswerNum === false) {
                return show(config('code.error'), $LanmeiCounselorAnswer->getError());
            }

            //判断与10个热门咨询师还差多少
            $nums = 10 - count($HotCounselor);

            for ($num = 0; $num < $nums; $num++) {
                if ($AnswerNum['list_data']) {
                    if ($num < count($AnswerNum['list_data'])) {
                        $arr = [
                            'id' => $AnswerNum['list_data'][$num]['cid'],
                            'name' => $AnswerNum['list_data'][$num]['nickname'],
                        ];
                        $data['hot'][] = $arr;
                    };
                }
            }
        } else {
            foreach ($HotCounselor as $datum) {
                $arr = [
                    'id' => $datum['id'],
                    'name' => $datum['nickname'],
                ];
                $data['hot'][] = $arr;
            }
        }

        return show(config('code.success'), '获取成功', $data);
    }


    /**
     * 咨询师认证状态接口
     * @return response\Json
     */
    public function AuthStatus()
    {
        $uid = $request->uid;

        $CounselorAuth = new LanmeiCounselorCheck();

        $data = $CounselorAuth->getAuthCheck($uid);

        if ($data === false) {
            return show(config('code.error'), $CounselorAuth->getError());
        }

        if (!$data) {
            $data['status'] = 0;
        }

        switch ($data['status']) {
            case 1:
                $arr = [
                    'status' => 1,
                    'title' => '审核中',
                    'msg' => '你已提交认证,正在等待审核',
                    'tips' => '提交有误'
                ];
                break;
            case 2:
                $arr = [
                    'status' => 2,
                    'title' => '审核未通过',
                    'msg' => '你的认证未通过审核,请重新提交认证',
                    'tips' => ''
                ];
                break;
            case 3:
                $arr = [
                    'status' => 3,
                    'title' => '审核通过',
                    'msg' => '您已通过审核,恭喜您成为占星师',
                    'tips' => '如资料有误,请点击'
                ];
                break;
            default:
                $arr = [
                    'status' => 0,
                    'title' => '未认证',
                    'msg' => '你暂未提交认证信息',
                    'tips' => ''
                ];
                break;
        }

        return show(config('code.success'), '获取成功', $arr);
    }


    /**
     * 获取咨询师认证信息接口
     * @return response\Json
     */
    public function AuthInfo()
    {
        $uid = $request->uid;

        $CounselorAuth = new LanmeiCounselorCheck();

        $data = $CounselorAuth->getAuthCheck($uid);

        if ($data === false) {
            return show(config('code.error'), $CounselorAuth->getError());
        }

        if ($data) {
            $arr = [
                'name' => $data['truename'],
                'telphone' => $data['telphone'],
                'ali_number' => $data['ali_number'],
                'id_number' => $data['id_number'],
                'left_pic' => $data['left_pic'],
                'right_pic' => $data['right_pic'],
                'intro' => $data['intro'],
                'nickname' => $data['nickname']
            ];

            return show(config('code.success'), '获取成功', $arr);
        } else {
            return show(config('code.error'), '你暂未提交认证信息');
        }
    }


    /**
     * 检查认证信息是否有重复
     * @param $uid
     * @param array $data
     * @return bool|response\Json
     */
    public function checkAuth($uid, $data = [])
    {
        $CounselorAuth = new LanmeiCounselorCheck();
        //判断所有认证是否有重复的
        $AllAuthInfo = $CounselorAuth->getAuthCheck($uid, $data['id_number'], $data['nickname']);

        if ($AllAuthInfo === false) {
            return show(config('code.error'), $CounselorAuth->getError());
        }
        if ($AllAuthInfo) {
            if ($AllAuthInfo['id_number'] == $data['id_number']) {
                return show(config('code.error'), '当前身份证已被注册');
            }

            if ($AllAuthInfo['nickname'] == $data['nickname']) {
                return show(config('code.error'), '当前咨询师名称已被注册');
            }
        }

        return true;
    }


    /**
     * 咨询师添加或编辑认证(审核认证通过后)接口
     * 测评通过后才可认证
     * 修改审核已通过的认证则需生成新的认证信息  , 修改审核未通过的编辑信息
     * @return response\Json
     */
    public function Auth(Request $request)
    {
        //后端判断新增/编辑
        $param = $request->only(['name', 'telphone', 'id_number', 'left_pic', 'right_pic', 'intro', 'nickname']);

        $validate = new Counselor();

        if ($validate->scene('auth')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }

        $uid = $request->uid;
        $CounselorAuth = new LanmeiCounselorCheck();

        //检测是否通过测评
        $ExerciseStatus = $this->getExerciseType();
        $is_auth = false;
        if ($ExerciseStatus['test_list']) {
            foreach ($ExerciseStatus['test_list'] as $et) {
                if (in_array($et['pid'], [2, 3]) && $et['is_test'] == 1) {
                    $is_auth = true;
                }
            }
        }

        if ($is_auth === true) {
            //检查认证信息是否有重复
            $this->checkAuth($uid, $param);

            //获取用户最新的认证数据
            $AuthInfo = $CounselorAuth->getAuthCheck($uid, 1);
            if ($AuthInfo === false) {
                return show(config('code.error'), $CounselorAuth->getError());
            }

            //新增,若无认证信息或审核完成
            if (!$AuthInfo || in_array($AuthInfo['status'], [2, 3])) {

                $arr = [
                    'uid' => $uid,
                    'truename' => $param['name'],
                    'telphone' => $param['telphone'],
                    'id_number' => $param['id_number'],
                    'left_pic' => $param['left_pic'],
                    'right_pic' => $param['right_pic'],
                    'intro' => $param['intro'],
                    'create_time' => time(),
                    'status' => 1,
                    'nickname' => $param['nickname'],
                ];
                $auth_re = $CounselorAuth->saveAuth($arr);
                if ($auth_re === false) {
                    return show(config('code.error'), $CounselorAuth->getError());
                }

                //将认证信息加入队列
                counselor_identity_job($auth_re);
            } //编辑,待审核状态中
            elseif ($AuthInfo['status'] == 1) {
                $arr = [
                    'uid' => $uid,
                    'truename' => $param['name'],
                    'telphone' => $param['telphone'],
                    'id_number' => $param['id_number'],
                    'left_pic' => $param['left_pic'],
                    'right_pic' => $param['right_pic'],
                    'intro' => $param['intro'],
                    'create_time' => time(),
                    'status' => 1,
                    'nickname' => $param['nickname'],
                ];
                $auth_re = $CounselorAuth->saveAuth($arr, $AuthInfo);
                if ($auth_re === false) {
                    return show(config('code.error'), $CounselorAuth->getError());
                }
            } else {
                return show(config('code.error'), '违规操作');
            }

            return show(config('code.success'), '保存成功', [
                'status' => 1,
                "title" => "已提交，待审核",
                "msg" => "您的资料已提交成功，我们将尽快审核，预计5个工作日反馈结果，请随时留意软件消息",
                "tips" => "如资料有误，"
            ]);
        } else {
            return show(config('code.error'), '通过占星或占卜测评后,才可认证');
        }
    }

    // /**
    //  * 获取测试类型及测试剩余次数和通过状态等
    //  * @return array|response\Json
    //  */
    // protected function getExerciseType()
    // {
    //     $uid = $request->uid;

    //     $ExerciseType = new LanmeiCounselorExerciseType();
    //     $ExerciseStatus = new LanmeiUserCounselorStatus();

    //     //获取习题类型
    //     $exercise = $ExerciseType->getUserExerciseType();
    //     var_dump($exercise);die;

    //     if ($exercise === false) {
    //         return show(config('code.error'), $ExerciseType->getError());
    //     }
    //     //获取用户习题状态
    //     $exercise_status = $ExerciseStatus->getUserCounselorStatus($uid);

    //     $arr = [
    //         'agreement' => '',
    //         'test_list' => []
    //     ];
    //     if ($exercise) {
    //         foreach ($exercise as $ex) {
    //             $status = 0;
    //             //判断考核是否通过
    //             if ($exercise_status) {
    //                 if ($ex['id'] == 1 && $exercise_status['xzdr_test'] == 1) {
    //                     $status = 1;
    //                 } elseif ($ex['id'] == 2 && $exercise_status['stargazer_test'] == 1) {
    //                     $status = 1;
    //                 } elseif ($ex['id'] == 3 && $exercise_status['divination_test'] == 1) {
    //                     $status = 1;
    //                 }
    //             }

    //             //用户剩余考核次数进行缓存
    //             $num = Cache::has('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $ex['id']);
    //             if ($num === null) {
    //                 $num = 3;
    //                 Cache::set('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $ex['id'], $num, 86400);
    //             } elseif ((int)$num === 0) {
    //                 $msg = '今天的答题机会已用完，明天再来吧~';
    //             }

    //             $arr['test_list'][] = [
    //                 'pid' => $ex['id'],
    //                 'p_img' => $ex['img'],
    //                 'p_title' => $ex['name'],
    //                 'p_des' => $ex['description'],
    //                 'test_time' => $ex['time'],
    //                 'p_num' => $ex['num'],
    //                 'is_test' => $status,
    //                 'test_num' => (int)$num,
    //                 'msg' => $msg ?? '',
    //             ];
    //         }
    //     } else {

    //         return show(config('code.error'), '暂无习题');
    //     }

    //     return $arr;
    // }
   /**
     * 获取测试类型及测试剩余次数和通过状态等
     * @return array|\think\response\Json
     */
    protected function getExerciseType()
    {
        $uid = $request->uid;

        $ExerciseType = new LanmeiCounselorExerciseType();
        $ExerciseRecord = new LanmeiCounselorExerciseRecord();
        $ExerciseStatus = new LanmeiUserCounselorStatus();

        //获取习题类型
        $exercise = $ExerciseType->getUserExerciseType();
        if ($exercise === false)
        {
            return show(config('code.error'), $ExerciseType->getError());
        }

        //获取用户习题状态
        $exercise_status = $ExerciseStatus->getUserCounselorStatus($uid);

        //获取用户今日习题次数
        $exercise_record = $ExerciseRecord->getUserExerciseRecord($uid);
        if ($exercise_record === false)
        {
            return show(config('code.error'), $ExerciseRecord->getError());
        }

        $arr = [
            'agreement' => '',
            'test_list' => []
        ];
        if ($exercise)
        {
            foreach ($exercise as $ex)
            {
                $num = 3;
                $msg = '';
                $status = 0;
                if ($exercise_record)
                {
                    foreach ($exercise_record as $exr)
                    {
                        if ($ex['id'] == $exr['cet_id'])
                        {
                            $num -= 1;
                        }
                        $num = Cache::get('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $ex['id']);
                        if ($num === false) {
                            Cache::set('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $ex['id'], intval($num), 86400);
                         }
                    }

                }
                   $num = Cache::get('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $ex['id']);
                    if ($num === false) {
                        $num = 3;
                        Cache::set('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $ex['id'], intval($num), 86400);
                     }
                    if ($num == 0)
                    {
                        $msg = '今天的答题机会已用完，明天再来吧~';
                    }
                //             //用户剩余考核次数进行缓存

                if ($exercise_status)
                {
                    if ($ex['id'] == 1 && $exercise_status['xzdr_test'] == 1)
                    {
                        $status = 1;
                    } elseif ($ex['id'] == 2 && $exercise_status['stargazer_test'] == 1)
                    {
                        $status = 1;
                    } elseif ($ex['id'] == 3 && $exercise_status['divination_test'] == 1)
                    {
                        $status = 1;
                    }
                }

                $arr['test_list'][] = [
                    'pid' => $ex['id'],
                    'p_img' => $ex['img'],
                    'p_title' => $ex['name'],
                    'p_des' => $ex['description'],
                    'test_time' => $ex['time'],
                    'p_num' => $ex['num'],
                    'is_test' => $status,
                    'test_num' => intval($num),
                    'msg' => $msg,
                ];
            }
        } else
        {

            return show(config('code.error'), '暂无习题');
        }

        return $arr;
    }
    /**
     * 测评类型及状态接口
     * @return response\Json
     */
    public function ExamineTypeStatus()
    {
        $arr = $this->getExerciseType();
        return show(config('code.success'), '获取成功', $arr);
    }


    /**
     * 测评题目内容接口
     * @return response\Json
     */
    public function ExamineContent(Request $request)
    {
        $param = $request->only(['pid']);
        $uid = $request->uid;

        $validate = new Counselor();

        if ($validate->scene('ExamineContent')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }

        //判断用户当前类型测评状态
        $ExerciseType = $this->getExerciseType();
        $num = 0;
        if ($ExerciseType['test_list']) {
            foreach ($ExerciseType['test_list'] as $et) {
                if ($et['pid'] == $param['pid']) {
                    //用户剩余考核次数进行缓存
                    $residue_num = Cache::has('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $et['pid']);
                    if ($residue_num == 0) {
                        return show(config('code.error'), '今天的答题机会已用完，明天再来吧~');
                    } else {
                        //没获取一次考核内容就减少一次考核机会
                        $residue_num = $residue_num - 1;
                        Cache::set('u' . $uid . ':' . date('Y-m-d', time()) . ':counselor_exercise_num:' . $et['pid'], $residue_num, 86400);
                    }
                }

                if ($et['pid'] == 1 && $et['is_test'] == 0 && $param['pid'] != 1) {
                    return show(config('code.error'), '请先通过星座达人测试哦~');
                }

                if ($et['pid'] == $param['pid'] && $et['is_test'] == 1) {
                    return show(config('code.error'), '您已通过认证');
                }
                if ($et['pid'] == $param['pid']) {
                    $num = $et['p_num'];
                }

                if ($param['pid'] == $et['pid']) {
                    //缓存用户答题开始的时间
                    Cache::set($uid . ':examine:time_remaining:' . $et['pid'], time(), $et['test_time']);
                }
            }
        }

        $Exercise = new LanmeiCounselorExercise();

        //随机获取N条题目
        $exercise = $Exercise->getExerciseId($param['pid'], $num);
        if ($exercise === false) {
            return show(config('code.error'), $Exercise->getError());
        }

        foreach ($exercise as $k => $ex) {
            $exercise[$k]['answer'] = [
                $ex['option_a'],
                $ex['option_b'],
                $ex['option_c'],
                $ex['option_d'],
            ];
            unset($exercise[$k]['option_a']);
            unset($exercise[$k]['option_b']);
            unset($exercise[$k]['option_c']);
            unset($exercise[$k]['option_d']);
            unset($ex['answer']);
        }
        $arr = [
            'total' => count($exercise),
            'exercise_content' => $exercise
        ];

        return show(config('code.success'), '获取成功', $arr);
    }


    /**
     * 获取测评剩余时间
     * @return float|int|response\Json
     */
    public function getTimeRemaining($map = [])
    {
        $uid = $request->uid;
        $validate = new Counselor();

        if ($validate->scene('TimeRemaining')->check($map) !== true) {
            return show(config('code.error'), $validate->getError());
        }

        //获取用户答题开始的时间
        //        $start_time = 1557738116;
        $start_time = Cache::get($uid . ':examine:time_remaining:' . $map['pid']);
        if ($start_time === false) {
            return false;
        }

        //获取用户的答题时间
        $answer_time = time() - $start_time;

        //获取所有测评类型信息
        $Examine = $this->getExerciseType();
        $array = [];
        if (!empty($Examine['test_list'])) {
            foreach ($Examine['test_list'] as $item) {
                //获取当前测评类型的总时长
                if ($item['pid'] == $map['pid']) {
                    $test_time = $item['test_time'];
                    $test_num = $item['test_num'];
                }
            }

            $array = [
                'test_time' => $test_time,
                'test_num' => $test_num,
                'answer_time' => $answer_time
            ];
        }
        //若答题时间超出总时间,退出
        if ($answer_time > $test_time) {
            return false;
        } else {
            return $array;
        }
    }

    /**
     * 答题剩余时间接口
     * @return response\Json
     */
    public function TimeRemaining(Request $request)
    {
        $param = $request->only(['type']);
        $time = $this->getTimeRemaining(['pid' => $param['type']]);

        if ($time === false) {
            return show(config('code.success'), '回答超时,请重新考核', ['time' => 0]);
        } else {
            return show(config('code.success'), '获取成功', ['time' => ($time['test_time'] - $time['answer_time']) * 1]);
        }
    }

    /**
     * 提交测评接口
     * pid 1达人 2占星 3占卜
     * @return response\Json
     */
    public function SubmitExamine(Request $request)
    {
        $param = $request->only(['pid', 'content']);
        $param['time'] = time();
        $validate = new Counselor();

        if ($validate->scene('SubmitExamine')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }


        //获取剩余考试时间
        $ExerciseType = $this->getTimeRemaining(['pid' => $param['pid']]);
        $uid = $request->uid;
        $Exercise = new LanmeiCounselorExercise();
        $ExerciseRecord = new LanmeiCounselorExerciseRecord();
        $ExerciseStatus = new LanmeiUserCounselorStatus();

        $content = json_decode($param['content'], true);

        $time = time();

        //若当前类型的答题次数已用完就退出
        if ($ExerciseType['test_num'] == 0) {
            return show(config('code.error'), '今天的答题机会已用完，明天再来吧~');
        } elseif ($content) {
            $ids = [];
            foreach ($content as $c) {
                $ids[] = $c['id'];
                $user_answer[$c['id']] = $c['answer'];
            }
            //获取当前提交的习题信息
            $exercise = $Exercise->getExerciseInfo($ids, $param['pid']);

            if ($exercise === false) {
                return show(\config('code.error'), $Exercise->getError());
            }
            //总分数
            $total = 100;
            //总题数
            $num = count($exercise);
            //最终用户得分
            $final_score = 0;
            //答对的题目数
            $total_num = 0;
            //多选答对的次数
            $right_times = 0;

            //②对比习题获取分数
            if (is_array($exercise) && !empty($exercise)) {
                //每题平均分
                $average_score = $total / $num;

                foreach ($exercise as $ex) {
                    $answer = explode(',', $ex['answer']);
                    //单选答对得分
                    if (count($answer) == 1 && $user_answer[$ex['id']] == $ex['answer']) {
                        $final_score += $average_score;
                        $total_num += 1;
                    } //多选全答对得分
                    elseif (count($answer) > 1 && $user_answer[$ex['id']] == $ex['answer']) {
                        $final_score += $average_score;
                        $total_num += 1;
                    } //多选部分答对得分
                    elseif (count($answer) > 1 && $user_answer[$ex['id']] !== $ex['answer']) {

                        $now_answer = explode(',', $user_answer[$ex['id']]);

                        if ($now_answer) {
                            foreach ($now_answer as $uw) {
                                if (in_array($uw, $answer)) {
                                    $right_times += 1;
                                }
                            }
                        }

                        //计算用户最终得分
                        $final_score += floor($right_times / count($answer) * $average_score * 0.5);
                    }
                }
            }
            // 写入答题记录
            $record_data = [
                'uid' => $uid,
                'content' => json_encode($content, true),
                'grade' => $final_score,
                'cet_id' => $param['pid'],
                'exercise_time' => $ExerciseType['answer_time'],
                'create_time' => $time,
                //                'max_time'=>$ExerciseType['answer_time']
            ];
            //保存答题记录
            $ExerciseRecord->saveUserExerciseRecord($record_data);
            //获取 用户 咨询师等级/测评结果/及状态
            $userCounselorInfo = $ExerciseStatus->getUserCounselorStatus($uid);
            $ischeck = $userCounselorInfo['is_check'] ?? 0;

            $typeName = [
                1 => '占星达人',
                2 => '占星师',
                3 => '占卜师'
            ];
            if ($final_score > 90) {   // 分数达标  更新测评状态
                $result = 1; // 通过
                //保存答题结果
                if ($userCounselorInfo && $userCounselorInfo['create_time'] > 0) {   //编辑
                    $tname = $param['pid'] == 2 ? 'stargazer' : 'divination';
                    $status_data = [
                        'uid' => $uid,
                        'update_time' => $time,
                        $tname . '_level' => 1,
                        $tname . '_test' => 1,
                    ];

                    if ($userCounselorInfo['status'] > 0) // 如果已经是占卜/占星师了
                    {
                        $status_data['status'] = 3; //两者皆是

                        $tips = '恭喜你通过了' . $typeName[$param['pid']] . '考核！\n正式成为' . $typeName[$param['pid']] . '！';
                    } else {
                        $tips = '恭喜你通过了' . $typeName[$param['pid']] . '考核！\n只要再通过实名认证后你就是' . $typeName[$param['pid']] . '啦！';
                    }
                    $ExerciseStatus->updateUserCounselorStatus($uid, $status_data);
                } else {
                    $status_data = [
                        'uid' => $uid,
                        'create_time' => $time,
                        'update_time' => $time,
                        'divination_level' => 0,
                        'stargazer_level' => 0,
                        'xzdr_test' => 1,
                        'divination_test' => 0,
                        'stargazer_test' => 0,
                        'is_check' => 0,
                        'status' => 0,
                        'counselor_status' => 1,
                        'c_id' => 0
                    ];
                    $tips = '恭喜你通过了' . $typeName[$param['pid']] . '考核！\n只要再通过实名认证后你就是' . $typeName[$param['pid']] . '啦！';
                    //新增
                    $ExerciseStatus->updateUserCounselorStatus($uid, $status_data);
                }
            } else {
                $result = 2;
                $tips = '成绩大于90分才能通过测试！\n加油哦~';
            }

            //测评超时
            if ($ExerciseType === false) {
                $result = 3;
            }
            //默认考试次数
            $exercise_num = ['一', '两'];

            if ($ExerciseType['test_num'] == 0) {
                $title = '本周您已没有考试机会';
            } else {
                if ($ExerciseType['test_num'] <= 1) {
                    $title = '本周您的测评机会已用完,请下周继续努力';
                } else {
                    $title = '本周您还有' . $exercise_num[$ExerciseType['test_num'] - 2] . '次机会';
                }
            }

            $data = [
                'grade' => round($final_score, 0),
                'flag' => $result,
                'exercise_tips' => $title,
                'total_num' => $num,
                'success_num' => $total_num,
                'tips' => $tips,
                'is_check' => $ischeck
            ];

            return show(config('code.success'), '提交成功', $data);
        }
    }


    /**
     * 是否接单接口
     * @return response\Json
     */
    public function IsTakeOrder(Request $request)
    {
        $param = $request->only(['status']);

        $validate = new Counselor();

        if ($validate->scene('IsTakeOrder')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }

        $uid = $request->uid;

        $LanmeiCounselor = new LanmeiCounselor();
        $CounselorInfo = $LanmeiCounselor->getCounselorInfo(['uid' => $uid]);
        if ($CounselorInfo === false) {
            return show(config('code.error'), $LanmeiCounselor->getError());
        } else {
            $arr = [
                'state' => $param['status']
            ];
            $res = $LanmeiCounselor->saveCounselor($arr, $CounselorInfo['id']);
            if ($res === false) {
                return show(config('code.error'), $LanmeiCounselor->getError());
            } else {
                return show(config('code.success'), '操作成功');
            }
        }
    }

    /**
     * 咨询师主页信息接口
     * @return response\Json
     * @throws \Exception
     * @throws \app\common\lib\exception\ApiException
     */
    public function CounselorHome(Request $request)
    {
        $param = $request->only(['cid']);

        $validate = new Counselor();

        if ($validate->scene('CounselorHome')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }

        $uid = $request->uid;
        $LanmeiCounselor = new LanmeiCounselor();
        $CounselorAnswer = new LanmeiCounselorAnswer();

        $Recode = new Recode();
        $Counselor = $LanmeiCounselor->getInfoById($param['cid']);
        if ($Counselor === false) {
            return show(config('code.error'), $LanmeiCounselor->getError());
        }
        if ($Counselor) {
            $SelfInfo = $Recode->getSelfRecode(['uid' => $uid]);
            $RecodeInfo = $Recode->getRecodeWithAstro(['id' => $SelfInfo['id']]);
            //获取咨询师全部回答数
            $AllAnswerNum = $CounselorAnswer->getCountAllAnswer($param['cid']);
            if ($AllAnswerNum === false) {
                return show(config('code.error'), $CounselorAnswer->getError());
            }
            //获取咨询师被采纳的回答数
            $AcceptAnswerNum = $CounselorAnswer->getCountAcceptAnswer($param['cid']);
            if ($AcceptAnswerNum === false) {
                return show(config('code.error'), $CounselorAnswer->getError());
            }
            //获取最多的五个评价标签
            $tags = LanmeiCommentTag::getCounselorComment($param['cid']);
            if ($AllAnswerNum) {
                $accept = round($AcceptAnswerNum / $AllAnswerNum, 2) * 100;
            } else {
                $accept = 0;
            }

            if ($uid == $Counselor['uid']) {
                $is_me = 1;
            } else {
                $is_me = 0;
            }
            $arr = [
                'avatar' => $Counselor['avatar'],
                'nickname' => $Counselor['nickname'],
                'sex' => $Counselor['sex'],
                'sun' => $RecodeInfo['sun'],
                'moon' => $RecodeInfo['moon'],
                'asc' => $RecodeInfo['asc'],
                'divination_integral' => $Counselor['divination_integral'],
                'stargazer_integral' => $Counselor['stargazer_integral'],
                'star_level' => $Counselor['star_level'],
                'grab_num' => $Counselor['grab_num'],
                'state' => $Counselor['state'],
                'divination_level' => $Counselor['divination_level'],
                'stargazer_level' => $Counselor['stargazer_level'],
                'divination_price' => $Counselor['divination_price'],
                'stargazer_price' => $Counselor['stargazer_price'],
                'intro' => $Counselor['intro'],
                'is_me' => $is_me,
                'accept' => $accept . '%',
                'user_comment' => array_values($tags)
            ];
            return show(config('code.success'), '成功', $arr);
        } else {
            return show(config('code.error'), '当前咨询师不存在');
        }
    }

    /**
     * 标签接口
     */
    public function getTag(Request $request)
    {
        $type = $request->input('type', 0);
        $param['tag_type'] = $type;
        $validate = new Counselor();

        if ($validate->scene('getTag')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }

        $tag = LanmeiTag::getTag($param['tag_type']);

        $arr = [
            'tag_list' => $tag
        ];

        return show(config('code.success'), '获取成功', $arr);
    }

    /**
     * 周榜接口
     */
    public function weeklyCharts()
    {
        $LanmeiCounselorAnswer = new LanmeiCounselorAnswer();
        $LanmeiCounselor = new LanmeiCounselor();
        //获取当前用户的咨询师信息
        $UserCounselor = $LanmeiCounselor->getCounselorInfo(['uid' => $request->uid]);
        //获取前二十咨询师的信息
        $AnswerNum = $LanmeiCounselorAnswer->getWeekBestCounselor($UserCounselor);

        return show(config('code.success'), '获取成功', $AnswerNum);
    }

    /**
     * 检查支付宝是否已被绑定
     * @param array $data
     * @return bool|response\Json
     */
    public function checkAli($data = [])
    {
        $CounselorAli = new LanmeiUserBindAlipay();
        //判断当前支付宝账号是否已经绑定
        $AliInfo = $CounselorAli->getAliNumberInfo($data['alipay_account']);
        if ($AliInfo === false) {
            return show(config('code.error'), $CounselorAli->getError());
        }
        if ($AliInfo) {
            return show(config('code.error'), '当前支付宝已被绑定');
        }

        return true;
    }

    /**
     * 检查当前用户审核状态
     * @param int $uid
     * @return array|bool|false|mixed|\PDOStatement|string|Model|response\Json
     */
    public function checkAuthStatus($uid = 0)
    {
        $CounselorAuth = new LanmeiCounselorCheck();
        $Auth = $CounselorAuth->getAuthCheck($uid);

        if ($Auth) {
            // 审核中不可绑定,只有审核通过的才进行表操作
            if ($Auth['status'] == 1) {

                return show(config('code.error '), '您有待审核的认证信息');
            } elseif ($Auth['status'] == 2) {

                return show(config('code.error '), '您的认证信息未通过审核,请重新认证!');
            }
            return $Auth;
        } else {
            return show(config('code.error '), '请先进行实名认证');
        }
    }


    /**
     * 绑定支付宝接口
     * @return response\Json
     */
    public function bindAli(Request $request)
    {
        $param = $request->only(['name', 'alipay_account']);

        $validate = new Counselor();

        if ($validate->scene('bindAli')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }

        $uid = $request->uid;

        //检查支付宝是否已被绑定
        $this->checkAli($param);

        $CounselorAuth = new LanmeiCounselorCheck();
        $CounseInfo = new LanmeiCounselorInfo();
        $CounselorAli = new LanmeiUserBindAlipay();
        $Info = $CounseInfo->getAuthInfo($uid);

        //检查审核状态并获取审核数据
        $Auth = $this->checkAuthStatus($uid);

        //修改通过表的支付宝信息
        if ($Info) {
            $info_res = $CounseInfo->saveInfo(['ali_number' => $param['alipay_account']], $Info);
            if ($info_res === false) {
                return show(config('code.error'), $CounseInfo->getError());
            }
        } else {
            return show(config('code.error '), '请先进行实名认证');
        }

        //修改审核表的支付宝信息
        $auth_res = $CounselorAuth->saveAuth(['ali_number' => $param['alipay_account']], $Auth);
        if ($auth_res === false) {
            return show(config('code.error'), $CounselorAuth->getError());
        }

        //添加支付宝数据
        $ali = [
            'uid' => $uid,
            'truename' => $param['name'],
            'alipay_account' => $param['alipay_account'],
            'create_time' => time()
        ];
        $ali_re = $CounselorAli->saveAli($ali);
        if ($ali_re === false) {
            return show(config('code.error'), $CounselorAli->getError());
        }

        return show(config('code.success'), '绑定成功');
    }

    /**
     * 解绑支付宝接口
     * @return response\Json
     */
    public function unbindAli()
    {
        $uid = $request->uid;

        $CounselorAli = new LanmeiUserBindAlipay();
        $CounselorAuth = new LanmeiCounselorCheck();
        $CounselorInfo = new LanmeiCounselorInfo();

        //检查审核状态并获取审核数据
        $Auth = $this->checkAuthStatus($uid);

        //获取当前绑定的支付宝信息
        $AliInfo = $CounselorAli->getAliNumberInfo($uid);

        if ($AliInfo) {
            //获取当前用户是否有认证信息,且认证时是否绑定了支付宝
            $Info = $CounselorInfo->getAuthInfo($uid);
            //修改通过表的支付宝信息
            if ($Info) {
                $info_res = $CounselorInfo->saveInfo(['ali_number' => ''], $Info);
                if ($info_res === false) {
                    return show(config('code.error'), $CounselorInfo->getError());
                }
            } else {
                return show(config('code.error '), '请先进行实名认证');
            }

            //修改审核表的支付宝信息
            $auth_res = $CounselorAuth->saveAuth(['ali_number' => ''], $Auth);
            if ($auth_res === false) {
                return show(config('code.error'), $CounselorAuth->getError());
            }

            $res = $CounselorAli->delAli($uid);

            if ($res === false) {
                return show(config('code.error'), $CounselorAli->getError());
            } else {
                return show(config('code.success'), '解绑成功');
            }
        } else {
            return show(config('code.error'), '当前用户未绑定支付宝');
        }
    }

    /**
     * 咨询师去回答问题
     */
    public function problemToAnswer(Request $request)
    {
        $params['cp_id'] = $request->input('cp_id', 0);
        $params['type'] = $request->input('type', 0);
        $params['content'] = $request->input('content', '');
        $params['duration'] = $request->input('duration', 0);
        $params['is_grab'] = $request->input('is_grab', 0);
        $uid = $request->uid;
        $answerType = 0; // 答题方式 1指定 2抢答 3普通回答
        // 参数校验
        $validateResult = $this->answerParamValidate($params);
        if ($validateResult['error']) {
            return show(config('code.error'), $validateResult['msg']);
        }
        // 通过问题ID 获取问题详情
        $conselorProblemModel = new LanmeiCounselorProblem();
        // 获取问题信息
        $problemInfo = $conselorProblemModel->getProblemInfoById($params['cp_id'], 'problem_type,counselor_mode,problem_status,update_time,people,answer_people,answer_ids');

        // 获取用户咨询师信息
        $counselorStatus = (new LanmeiUserCounselorStatus())->getUserCounselorStatus($uid);
        if (!$counselorStatus || !in_array($counselorStatus['status'], [3, $problemInfo['problem_type']])) {
            $m = $problemInfo['problem_type'] == 1 ? '占星' : '占卜';
            return show(config('code.error'), '您还不是' . $m . '师');
        }

        // 获取用户已经回答的问题ID数据--> 判断用户是否已经回答过当前问题 或者当前问题是自己提问的
        $answerModel = (new LanmeiCounselorAnswer());

        if (in_array($params['cp_id'], $conselorProblemModel->getUserProblemIds($uid))) {
            return show(config('code.error'), '自己悬赏的问题不能进行回复');
        }

        if (in_array($params['cp_id'], $answerModel->getCounselorAnswerToProblemCpIds($counselorStatus['c_id']))) {
            return show(config('code.error'), '问题已经回复过了！');
        }
        $problemIoc = ProblemAndAnswer::getInstance()->setCacheKey($problemInfo['problem_type']);
        switch ($problemInfo['counselor_mode']) {
            case 1: // 指定
                // 如果不在待回复状态 或 没有已经距离提问时间大于24小时
                if ($problemInfo['problem_status'] != 3 || $problemInfo['update_time'] + 86400 < time()) {
                    return show(config('code.error'), '已经过了答题时间！');
                } else {
                    $answerType = 1;
                }
                break;
            case 2: // 公开
                // 回答抢答的问题 && 判断当前抢答历史记录表是否真的有自己抢到并是待回答状态的问题
                if ($params['is_grab'] && LanmeiCounselorGrabRecord::getPendingGrabAnswer($params['cp_id'], $counselorStatus['c_id'])) {
                    $answerType = 2;
                    break;
                }
                // 普通回答逻辑------
                if ($problemInfo['people'] <= $problemInfo['answer_people']) {
                    return show(config('code.error'), '预计回答人数已满！看看其他的问题吧..');
                }

                if ($problemInfo['problem_status'] != 3) {
                    return show(config('code.error'), '问题已经过了可回答时间了');
                }
                // 去问题池中 获取问题ID  成功则去答题 失败则 返回答题人数已满提示
                /* $result = $problemIoc->popProblem($params['cp_id']);
                if (!$result)
                {
                    return show(config('code.error'), '预计回答人数已满！看看其他的问题吧..');
                }*/

                $answerType = 3;
                break;
            default:
                return show(config('code.error'), '问题异常！');
        }

        $answerData = [
            'cp_id' => $params['cp_id'], // 问题ID
            'c_id' => $counselorStatus['c_id'], //咨询师ID
            'answer_type' => $params['type'], // 答题方式 1语音 2文本
            'answer_content' => $params['content'], // 答案内容
            'duration' => $params['duration'] // 时长
        ];

        // 去回答问题
        $result = $answerModel->answerToProblem($answerData, $answerType, $problemInfo);

        if (!$result['status']) { // 回答失败 并且是普通公开回答方式 将问题抛回问答池
            if ($answerType == 3) {
                $problemIoc->lpushProblem($params['cp_id']);
            }
            return show(config('code.error'), $result['msg']);
        }
        // 增加已回答 问题 的 问题ID缓存
        $answerModel->setCounselorAnswerToProblemCpIds($answerData['c_id'], $answerData['cp_id']);

        return show(config('code.success'), '答题成功');
    }

    /**
     * 回答参数校验
     * @param $params
     * @return array
     */
    protected function answerParamValidate($params)
    {
        if (!$params['cp_id']) {
            return ['error' => true, 'msg' => '问题不存在'];
        }

        if (!in_array($params['type'], [1, 2])) {
            return ['error' => true, 'msg' => '请求异常'];
        }

        if ($params['type'] == 1) { // 语音
            if (!$params['content']) {
                return ['error' => true, 'msg' => '语音答案不能为空'];
            }

            if ($params['duration'] < 60 || $params['duration'] > 120) {
                return ['error' => true, 'msg' => '音频回复时长须在60~120秒之间'];
            }
        } else { // 文本
            $length = mb_strlen((string)$params['content']);
            if ($length < 100 || $length > 300) {
                return ['error' => true, 'msg' => '文字回复须在100~300字直接'];
            }
        }

        return ['error' => false, 'msg' => ''];
    }

    /**
     * 抢单
     */
    public function grabProblem()
    {
        $uid = $request->uid;
        // 获取用户咨询师身份信息
        $userCounselorInfo = (new LanmeiUserCounselorStatus())->getUserCounselorStatus($uid);
        if (!$userCounselorInfo || $userCounselorInfo['status'] == 0) // 用户还不是咨询师
        {
            return show(config('code.error'), '服务器异常');
        }
        // 判断用户是否有待完成的问题
        $grabProblemId = LanmeiCounselorGrabRecord::getPendingGrabProblem($userCounselorInfo['c_id']);
        if ($grabProblemId) {
            return show(config('code.success'), '抢单成功', ['cp_id' => $grabProblemId]);
        }
        // 判断用户今天是否还有抢单次数
        if (LanmeiCounselorGrabRecord::getUserGrabUnfinishNumByDay($userCounselorInfo['c_id']) >= 3) {
            return show(config('code.error'), '今天已经没有抢答次数了');
        }

        $iocId = $userCounselorInfo['status'] == 3 ? rand(1, 2) : $userCounselorInfo['status'];
        // 抢单  去问题池 随机取一个问题
        $problemAndAnswerIoc = ProblemAndAnswer::getInstance()->setCacheKey($iocId);
        $cpId = $problemAndAnswerIoc->randPopProblem();

        if (
            !$cpId
            || in_array($cpId, (new LanmeiCounselorAnswer())->getCounselorAnswerToProblemCpIds($userCounselorInfo['c_id'])) // 判断自己是否已经回答过该问题
            || in_array($cpId, (new LanmeiCounselorProblem())->getUserProblemIds($uid)) // 判断问题是不是本人提交成创建的
        ) {
            if ($cpId) {
                // 抢单成功  但已经回答过问题 或者是本人提问的
                $problemAndAnswerIoc->lpushProblem($cpId); // 将问题抛回 问题池
            }
            return show(config('code.error'), '平台暂无可供抢答的提问');
        }
        // 记录抢单日志
        $data = [
            'c_id' => $userCounselorInfo['c_id'],
            'create_time' => time(),
            'cp_id' => $cpId,
            'type' => $iocId, // 问题类型 1占星 2占卜
            'status' => 0 // 待完成
        ];

        try {
            $grabRecordModel = new LanmeiCounselorGrabRecord();
            $res = $grabRecordModel->save($data);
            // 缓存抢答问题ID
            LanmeiCounselorGrabRecord::setCounselorGrabRecord($userCounselorInfo['c_id'], $cpId);
            // 添加过期回收队列
            $queueConfig = config('queue');
            queuePush($queueConfig['grab_problem_task'], ['id' => $grabRecordModel->id], $queueConfig['grab_problem_queue'], $queueConfig['grab_problem_delay']);
        } catch (Exception $e) {
            $problemAndAnswerIoc->lpushProblem($cpId); // 将问题抛回 问题池
            return show(config('code.error'), '平台暂无可供抢答的提问');
        }

        return show(config('code.success'), '抢单成功', ['cp_id' => $cpId]);
    }

    /**
     * 取消回答抢答的 问题
     */
    public function grabCancel()
    {
        $uid = $request->uid;
        // 获取用户咨询师身份信息
        $userCounselorInfo = (new LanmeiUserCounselorStatus())->getUserCounselorStatus($uid);
        if (!$userCounselorInfo || $userCounselorInfo['status'] == 0) // 用户还不是咨询师
        {
            return show(config('code.error'), '服务器异常');
        }
        // 获取
        $cpId = LanmeiCounselorGrabRecord::getPendingGrabProblem($userCounselorInfo['c_id']);
        // 取消抢答
        $result = LanmeiCounselorGrabRecord::grabCancel($cpId, $userCounselorInfo['c_id']);

        if ($result['status']) {
            return show(config('code.success'), '取消成功');
        } else {
            return show(config('code.error'), $result['msg']);
        }
    }

    /**
     * 问答回复列表
     */
    public function answerList(Request $request)
    {
        $cid = $request->input('cid', 0);
        $uid = $request->uid;

        $counselorStatusModel = new LanmeiUserCounselorStatus();
        // 获取用户咨询师状态信息
        $userCounselorStatus = $counselorStatusModel->getUserCounselorStatus($uid);
        // 判断是不是本人 是咨询师 且 （cid 和 自己的咨询师 id相同 或 参数cid为空）
        $isSelf = ($userCounselorStatus
            && $userCounselorStatus['c_id'] != 0
            && ($userCounselorStatus['c_id'] == $cid || $cid == 0)) ? true : false;
        // 如果自己是咨询师，cid又为0时 此时cid为自己的咨询师ID
        $cid = $cid == 0 && $isSelf ? $userCounselorStatus['c_id'] : $cid;

        if (!$cid) {
            return show(config('code.error'), '服务异常');
        }

        $data = (new LanmeiCounselorProblem())->getCounsoleAnswerToProblemList($cid, $isSelf);

        return show(config('code.success'), '问答回复', $data);
    }
}
